package Connection;

import Controllers.Application;
import Entities.World;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

public class WebWorldListLoader implements WorldListLoader {

    private String sessionID = null;
    private ArrayList<World> worldList;
    private Application application;

    public WebWorldListLoader(Application application) {
        this.application = application;
    }

    public URLConnection getConnection() {
        URLConnection urlConnection = null;
        IPServer iPServer = new IPServer(application);
        String location = iPServer.getAdress() + "/ArkanoidServidor/WorldListServlet";
        try {
            URL url = new URL(location);
            urlConnection = url.openConnection();
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.setUseCaches(false);
            urlConnection.setRequestProperty("Content-Type", "application/x-java-serialized-object");
            urlConnection.setRequestProperty("Cookie", "JSESSIONID=" + sessionID);
        } catch (Exception ex) {
            Logger.getLogger(WebWorldListLoader.class.getName()).log(Level.SEVERE, null, ex);
        }
        return urlConnection;
    }

    @Override
    public ArrayList<World> loadWorldList() {
        try {
            URLConnection connection = getConnection();

            OutputStream outputStream = connection.getOutputStream();
            ObjectOutputStream o = new ObjectOutputStream(outputStream);
            o.writeObject("1");
            o.flush();
            o.close();

            InputStream inputStream = connection.getInputStream();
            ObjectInputStream i = new ObjectInputStream(inputStream);
            worldList = (ArrayList<World>) i.readObject();
            sessionID = (String) i.readObject();
            return worldList;
        } catch (Exception ex) {
            Logger.getLogger(WebWorldListLoader.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
}
